package com.hulk.dryad.manage.framework.xss.config;

import com.hulk.dryad.manage.config.JacksonConfig;
import com.hulk.dryad.manage.framework.xss.core.*;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * jackson xss 配置
 *
 *  @author hulk
 */
@Configuration
@ConditionalOnProperty(name = "enabled", prefix = XssProperties.PREFIX, havingValue = "true", matchIfMissing = true)
@AutoConfigureAfter(JacksonConfig.class)
@EnableConfigurationProperties(XssProperties.class)
@RequiredArgsConstructor
public class XssCleanAutoConfiguration implements WebMvcConfigurer {

	private final XssProperties xssProperties;

	@Bean
	@ConditionalOnMissingBean
	public XssCleaner xssCleaner() {
		return new DefaultXssCleaner(xssProperties);
	}
	@Bean
	public FormXssClean formXssClean(XssCleaner xssCleaner) {
		return new FormXssClean(xssProperties,xssCleaner);
	}

	@Bean
	public Jackson2ObjectMapperBuilderCustomizer xssJacksonCustomizer(XssCleaner xssCleaner ) {
		JacksonXssClean xssClean = new JacksonXssClean(xssProperties,xssCleaner);
		return builder -> builder.deserializerByType(String.class, xssClean);
	}


	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		XssCleanInterceptor interceptor = new XssCleanInterceptor(xssProperties);
		registry.addInterceptor(interceptor).addPathPatterns(xssProperties.getPathPatterns())
				.excludePathPatterns(xssProperties.getPathExcludePatterns()).excludePathPatterns("/rest/heartbeat","/favicon.ico").order(Ordered.LOWEST_PRECEDENCE);
	}

}
